<template>
  <ex-dialog
    width="1200px"
    class="ex-diolog"
    :title="title"
    :visible="visible"
    :close-on-click-modal="false"
    @closeDialog="handleClose"
  >
    <div class="main" v-loading="loading">
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="140px" class="demo-ruleForm" :disabled="disabled">
        <div class="title">活动基本信息</div>
        <el-row>
          <el-col :span="12">
            <el-form-item label="活动名称：" prop="name">
              <el-input v-model="ruleForm.name" placeholder="请填写活动名称" maxlength="50"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="活动图片:" prop="activityImg"  ref="imgRef">
              <ImageUpload :limit="1" @successImg="successImg" :value="ruleForm.activityImg" @input="handleRemove"></ImageUpload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="活动时间：" prop="date"> 
              <el-date-picker
                v-model="ruleForm.date"
                @change="getTime"
                type="datetimerange"
                format="yyyy-MM-dd HH:mm:ss"
                value-format="yyyy-MM-dd HH:mm:ss"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                placeholder="选择日期时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="店铺名称：" prop="merchantId">
              <el-select v-model="ruleForm.merchantId" placeholder="请选择店铺" filterable  size="small" @change="changeMerchantId" :disabled="pathType == 'edit'">
                <el-option v-for="item in merchantIdList" :key="item.id" :label="item.value" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="店铺活动资产：" prop="merchantEquityCardId">
              <el-select v-model="ruleForm.merchantEquityCardId" placeholder="请选择资产" size="small" @change="changemerchantEquityCardId" :disabled="pathType == 'edit'">
                <el-option v-for="item in merchantEquityCardList" :key="item.id" :label="item.value" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row style="margin-bottom: 20px">
            <el-col :span="24">
              <el-table :data="ruleForm.selEquityCardList" stripe border>
                <el-table-column label="卡名称" align="center" prop="name" :show-overflow-tooltip="true" />
                <el-table-column label="卡功能" align="center" prop="customerPhone" :show-overflow-tooltip="true">
                  <template slot-scope="scope">
                    <dict-tag :options="equityCardType" :value="scope.row.type" />
                  </template>
                </el-table-column>
                <el-table-column label="发行方" align="center" prop="issuerName" :show-overflow-tooltip="true" />
                <el-table-column label="上链时间" align="center" prop="issueTime" :show-overflow-tooltip="true" />
                <el-table-column label="单价" align="center" prop="price" :show-overflow-tooltip="true" />
                <el-table-column label="库存总量" align="center" prop="total" :show-overflow-tooltip="true" />
                <el-table-column label="剩余库存" align="center" prop="usable" :show-overflow-tooltip="true" />
              </el-table>
            </el-col>
          </el-row>
        <el-row>
          <el-col :span="8" v-if="pathType == 'add'">
            <el-form-item label="活动库存：" prop="stock">
              <el-input placeholder="请输入活动库存" v-model="ruleForm.stock">
                <template slot="append">份</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="pathType == 'edit'">
            <el-form-item label="添加活动库存：">
              <el-input placeholder="请输入添加活动库存" v-model="ruleForm.stock">
                <template slot="append">份</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4" v-if="pathType == 'edit'">
            <div class="stockNum">剩余库存: {{residueStock}}</div>
          </el-col>
        </el-row>
        <div class="title">激励规则</div>
        <el-row>
          <el-col :span="12">
            <el-form-item label="积分激励：" prop="integralIncentive">
                <el-switch
                  v-model="ruleForm.integralIncentive"
                  active-value="1"
                  inactive-value="2">
                </el-switch>
            </el-form-item>
          </el-col>
        </el-row>
        <template v-if="ruleForm.integralIncentive == 1">
          <el-row>
            <el-col :span="12">
              <el-form-item label="激励规则：" prop="incentiveType">
                <el-select v-model="ruleForm.incentiveType" placeholder="请选择激励规则" size="small">
                  <el-option v-for="item in incentiveTypeList" :key="item.id" :label="item.value" :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="积分类型：" prop="integralType">
                <el-select v-model="ruleForm.integralType" placeholder="请选择积分类型" size="small">
                  <el-option v-for="item in integralTypeList" :key="item.id" :label="item.value" :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12" v-if="ruleForm.incentiveType == 2">
              <el-form-item label="激励数额：" prop="incentiveAmount">
                <el-input placeholder="请输入激励数额" v-model="ruleForm.incentiveAmount">
                  <template slot="append" v-if="ruleForm.integralType == 1">CoCo</template>
                  <template slot="append" v-if="ruleForm.integralType == 2">椰分</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12" v-if="ruleForm.incentiveType == 1">
              <el-form-item label="激励比例：" prop="incentiveAmount">
                <el-input placeholder="请输入激励比例" v-model="ruleForm.incentiveAmount">
                  <template slot="append">%</template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </template>
        <el-row>
          <el-col :span="12">
            <el-form-item label="勋章激励：" prop="medalIncentive">
                <el-switch
                  v-model="ruleForm.medalIncentive"
                  active-value="1"
                  inactive-value="2">
                </el-switch>
            </el-form-item>
          </el-col>
        </el-row>
        <template v-if="ruleForm.medalIncentive == 1">
          <el-row>
            <el-col :span="12">
              <el-form-item label="勋章名称：" prop="equityCardId">
                <el-select v-model="ruleForm.equityCardId" placeholder="请选择勋章" size="small"  @change="changeEquityCardId">
                  <el-option v-for="item in xzAssetList" :key="item.id" :label="item.value" :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row style="margin-bottom: 20px">
            <el-col :span="24">
              <el-table :data="ruleForm.selxzAssetList" stripe border>
                <el-table-column label="卡名称" align="center" prop="cardName" :show-overflow-tooltip="true" />
                <el-table-column label="卡功能" align="center" prop="customerPhone" :show-overflow-tooltip="true">
                  <template slot-scope="scope">
                    <dict-tag :options="equityFunctionType" :value="scope.row.functionType" />
                  </template>
                </el-table-column>
                <el-table-column label="发行方" align="center" prop="issuerName" :show-overflow-tooltip="true" />
                <el-table-column label="上链时间" align="center" prop="chainTime" :show-overflow-tooltip="true" />
                <el-table-column label="单价" align="center" prop="price" :show-overflow-tooltip="true" />
                <el-table-column label="库存总量" align="center" prop="total" :show-overflow-tooltip="true" />
                <el-table-column label="剩余库存" align="center" prop="usable" :show-overflow-tooltip="true" />
              </el-table>
            </el-col>
          </el-row>
        </template>
        <el-form-item label="活动详情：" prop="activityDetail" ref="activityDetailRef" :key="15" style="margin-top: 20px">
          <div class="richText">
            <Toolbar style="border-bottom: 1px solid #ccc" :editor="editor" :defaultConfig="toolbarConfig"
              :mode="mode" />
            <Editor style="height: 500px; overflow-y: hidden;" v-model="ruleForm.activityDetail" :defaultConfig="editorConfig"
              :mode="mode" @onCreated="onCreated"  @onChange="onChange"/>
          </div>
        </el-form-item>
      </el-form>
    </div>
    <div class="button_box">
      <el-button
        type="primary"
        :loading="AgreeLoading"
        @click="submitForm('ruleForm',2)"
      >保存提交</el-button>
      <el-button
        type="primary"
        :loading="AgreeLoading"
        @click="submitForm('ruleForm',1)"
        :disabled="pathType == 'edit'"
      >保存草稿</el-button>
      <el-button @click="handleClose">取消</el-button>
    </div>
  </ex-dialog>
</template>
<script>
import Loading from "@/components/Loading/index";
// api
import {
  addPackage,
  editPackage,
  shenyemerchant,
  shopasset,
  assetInfo,
  xzAsset,
  xzAssetInfo,
  packageInfo,
} from "@/api/assetPackage/activityList";
import '@wangeditor/editor/dist/css/style.css'
import {
  Editor,
  Toolbar
} from "@wangeditor/editor-for-vue";
export default {
  components: {
    Loading,
    Editor,
    Toolbar
  },
  props: {
    visible: Boolean,
    id: String,
    pathType: String,
  },
  data() {
    var checkValidityDay = (rule, value, callback) => {
      let regNumber = /^\+?[1-9]\d*$/; //大于0的正整数
      // console.log(value, this.ruleForm.couponValidityType)
      if (
        !value &&
        this.ruleForm.commodityList[this.arrayIndex].couponValidityType == 2
      ) {
        return callback(new Error("请输入数值"));
      } else if (
        regNumber.test(value) == false &&
        this.ruleForm.commodityList[this.arrayIndex].couponValidityType == 2
      ) {
        return callback(new Error("请输入大于0正整数"));
      } else {
        return callback();
      }
    };
    var checkStock = (rule, value, callback) => {
      //总库存限制数量校验
      let regNumber = /^\+?[1-9]\d*$/; //大于0的正整数
      if (!value) {
        return callback(new Error("请活动库存"));
      } else if (
        regNumber.test(value) == false
      ) {
        return callback(new Error("请输入大于0正整数"));
      } else {
        return callback();
      }
    };
    var checkLimitAmount = (rule, value, callback) => {
      //总库存限制数量校验
      let regNumber = /^\+?[1-9]\d*$/; //大于0的正整数
      if (!value && this.ruleForm.buyType == 2) {
        return callback(new Error("请输入数值"));
      } else if (regNumber.test(value) == false && this.ruleForm.buyType == 2) {
        return callback(new Error("请输入大于0正整数"));
      } else {
        return callback();
      }
    };
    var checkOriginalPrice = (rule, value, callback) => {
      //销售原价校验
      let regNumber = /(^[1-9](\d+)?(\.\d{1,2})?$)|(^\d\.\d{1,2}$)/; //大于0的数值且最多保留两位小数的数值
      if (regNumber.test(value) == false || value == "0.00" || value == "0.0") {
        return callback(new Error("请填写大于0且最多保留两位小数的数值"));
      } else {
        return callback();
      }
    };
    
    return {
      labelWidth: "150px",
      inputWidth: "420px",
      title: "新增资产包活动",
      loading: false,
      disabled: false,
      AgreeLoading: false,
      ruleForm: {
        name: "", //活动名称
        activityImg: "", //活动图片
        endTime: "", //活动结束时间
        startTime: "", //活动开始时间
        equityCardId: "", //数字权益卡id
        id: "", //神椰资产包id（编辑必填）
        incentiveAmount: "", //激励比例/激励数额
        incentiveType: "", //积分激励规则 1 交易金额比例 2 固定金额
        integralIncentive: "1", //积分激励 1 开启 2 关闭
        integralType: "", //积分类型 1 神椰Coco 2 椰分
        medalIncentive: "1", //勋章激励 1 开启 2 关闭
        merchantEquityCardId: "", //商家数字权益卡id
        merchantId: "", //商家id
        saveStatus: "", //保存状态 1 保存草稿 2 保存提交
        stock: "", //库存数量
        date: [], //活动时间（校验用）
        activityDetail: '',//活动详情
        selEquityCardList: [],
        selxzAssetList: [],
      },
      residueStock: 0,
      merchantIdList: [],//店铺下拉列表
      merchantEquityCardList: [],//店铺活动资产下拉
      xzAssetList: [],//勋章卡下拉
      advertiseTypeList: [],
      equityCardType: [],
      equityFunctionType: [],
      incentiveTypeList: [
        {id: '1',value: '按交易金额比例激励'},
        {id: '2',value: '按固定金额激励'},
      ],
      integralTypeList: [
        {id: '1',value: 'CoCo'},
        {id: '2',value: '椰分'},
      ],
      rules: {
        name: [
          { required: true,message: "请填写活动名称",trigger: ["change", "bulr"]}
        ],
        couponType: [
          {required: true,message: "请选择券类型",trigger: ["change"]}
        ],
        activityImg: [
          {required: true, message: "请上传活动图片",trigger: ["change"]}
        ],
        date: [
          {required: true,message: "请选择时间",trigger: ["change"]}
        ],
        merchantId: [
          {required: true,message: "请选择店铺",trigger: ["change"]}
        ],
        merchantEquityCardId: [
          { required: true,message: "请选择资产",trigger: ["change", "bulr"]}
        ],
        stock: [
          { validator: checkStock,required: true,trigger: ["change", "bulr"]}
        ],
        integralIncentive: [
          { required: true,message: "请选择激励规则",trigger: ["change", "bulr"]}
        ],
        incentiveType: [
          { required: true,message: "请选择激励规则",trigger: ["change", "bulr"]}
        ],
        integralType: [
          { required: true,message: "请选择积分类型",trigger: ["change", "bulr"]}
        ],
        incentiveAmount: [
          { required: true,message: "请输入",trigger: ["change", "bulr"]}
        ],
        medalIncentive: [
          { required: true,message: "请选择勋章激励",trigger: ["change", "bulr"]}
        ],
        equityCardId: [
          { required: true,message: "请选择勋章",trigger: ["change", "bulr"]}
        ],
        activityDetail: [
          { required: true,message: "请填写活动详情",trigger: ["change", "bulr"]}
        ],
      },
      // 富文本配置
      logoUploadUrlImg: process.env.VUE_APP_BASE_API + "/common/v1/uploadFile", //图片接口
      videoUploadUrl: process.env.VUE_APP_BASE_API + "/common/v1/uploadFile", //视频接口
      editor: null,
      html: "<p>hello&nbsp;world</p>",
      toolbarConfig: {
        // toolbarKeys: [ /* 显示哪些菜单，如何排序、分组 */ ],
        // excludeKeys: [ /* 隐藏哪些菜单 */ ],
        excludeKeys:['group-video']
      },
      editorConfig: {

        placeholder: "请输入内容...",
        // autoFocus: false,
        // 所有的菜单配置，都要在 MENU_CONF 属性下
        MENU_CONF: {},
      },
      mode: 'default', // or 'simple'
    };
  },
  computed: {},
  created() {
    if(this.pathType == 'edit'){
      this.title = '编辑资产包活动'
      this.ruleForm.id = this.id
      this.getInfo()
    }
    this.getshenyemerchant()
    this.getCouponTypeList();
    this.getxzAsset()
  },
  mounted() {
    var _this = this
    // 配置上传图片
    var name = ''
    this.editorConfig.MENU_CONF['uploadImage'] = {
      server: _this.logoUploadUrlImg,
      // headers: _this.headers,
      fieldName: 'file',
      maxFileSize: 5 * 1024 * 1024,
      //    async customUpload(file, insertFn) {
      //        console.log(file)
      //     // file 即选中的文件
      //     // 自己实现上传，并得到图片 url alt href
      //     // 最后插入图片
      //     //   insertFn(url, alt, href)
      //     },
      onSuccess(file, res) {
        name = file.name
        // console.log(`${file.name} 上传成功`, res)
      },
      // 上传错误，或者触发 timeout 超时
      onError(file, err, res) { 
          _this.$message.error(String(err))              // JS 语法
          // console.log(`${file.name} 上传出错`, err, res)
      },
      customInsert(res, insertFn) {
        console.log(res)
        insertFn(res.result.url, name, res.result.url)
      }
    }
    // 配置上传视频
    this.editorConfig.MENU_CONF['uploadVideo'] = {
      server: _this.videoUploadUrl,
      // headers: _this.headers,
      fieldName: 'file',
      maxFileSize: 500 * 1024 * 1024,
      //    async customUpload(file, insertFn) {
      //        console.log(file)
      //     // file 即选中的文件
      //     // 自己实现上传，并得到图片 url alt href
      //     // 最后插入图片
      //     //   insertFn(url, alt, href)
      //     },
      customInsert(res, insertFn) {
        // res 即服务端的返回结果
        // 从 res 中找到 url ，然后插入
        insertFn(res.result.url)
      },
    }
  },
  computed: {},
  methods: {
    onCreated(editor) {
      this.editor = Object.seal(editor); // 【注意】一定要用 Object.seal() 否则会报错
      console.log('this.editor',this.editor)
    },
    onChange(editor) {
      console.log("onChange", editor.getHtml()); // onChange 时获取编辑器最新内容
    },
    getEditorText() {
      const editor = this.editor;
      if (editor == null) return;

      console.log(editor.getText()); // 执行 editor API
    },
    printEditorHtml() {
      const editor = this.editor;
      if (editor == null) return;

      console.log(editor.getHtml()); // 执行 editor API
    },
    //获取详情
    getInfo(){
      var id = this.ruleForm.id
      packageInfo(id).then(res => {
        this.ruleForm = {
          ...res.result,
          date: []
        }
        this.residueStock = res.result.stock - res.result.soldStock
        this.ruleForm.stock = 0
        
        this.ruleForm.date[0] = res.result.startTime
        this.ruleForm.date[1] = res.result.endTime

        this.getshopasset()
        this.changemerchantEquityCardId(res.result.merchantEquityCardId)
        if(res.result.equityCardId){
          this.changeEquityCardId(res.result.equityCardId)
        }
      })
    },
    //获取券类型字典
    getCouponTypeList() {
      var dictType = "merchant_equity_card_type,equity_function_type";
      this.$getSelectList(dictType)
        .then(res => {
          this.equityCardType = res.result[0].dictList;
          this.equityFunctionType = res.result[1].dictList;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    //获取店铺下拉
    getshenyemerchant(){
      shenyemerchant().then(res => {
        this.merchantIdList = res.result
      })
    },
    //选择店铺
    changeMerchantId(e){
      console.log('e',e)
      this.ruleForm.merchantId = e
      this.getshopasset()
    },
    
    //获取店铺资产
    getshopasset(){
      var params = {
        merchantId: this.ruleForm.merchantId,
        id: this.ruleForm.id
      }
      shopasset(params).then(res => {
        this.merchantEquityCardList = res.result
      })
    },
    //选择店铺资产
    changemerchantEquityCardId(e){
      this.ruleForm.selEquityCardList = []
      console.log('哈哈哈')
      assetInfo(e).then(res => {
        var data = res.result
        console.log('data',data)
        this.ruleForm.selEquityCardList.push(data)
      })
    },
    //查询勋章卡下拉
    getxzAsset(){
      xzAsset().then(res => {
        this.xzAssetList = res.result
      })
    },
    
    //选择勋章
    changeEquityCardId(e){
      this.ruleForm.selxzAssetList = []
      xzAssetInfo(e).then(res => {
        var data = res.result
        console.log('data',data)
        this.ruleForm.selxzAssetList.push(data)
      })
    },
    //取消
    handleClose(formName) {
      this.$emit("update:visible", false);
    },
    
    
    deleteCommodityLs(index) {
      //删除到店产品设置
      this.ruleForm.commodityList.splice(index, 1);
    },
    /** 新增nfr产品设置 */
    addNfrLs() {
      this.ruleForm.nfrlist.push({
        id: "", //神椰打卡活动NFR信息id
        nfrType: "", //NFR卡功能类型 1权益NFR
        nfrStock: "", //NFR库存
        equityCardInventoryId: "", //NFR库存id
        nfrNewStock: "", //增加库存数量
        equityCardInventoryLs: []
      });
    },
    deleteNfrLs(item, index) {
      //删除nfr产品设置
      console.log(item);
      if (item.id != "" && this.dialogStatus != 2) {
        this.$confirm("删除释放锁定NFR库存，是否删除?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            let data = {
              nfrId: item.id,
              punchActivityId: this.id
            };
            nfrDeactivate(data).then(res => {
              this.$message({
                message: "操作成功",
                type: "success"
              });
              this.ruleForm.nfrlist.splice(index, 1);
            });
          })
          .catch(() => {});
      } else {
        this.ruleForm.nfrlist.splice(index, 1);
      }
    },
     //卡名称列表移除标签
    removeTag(e){
      var isShow = this.ruleForm.blockNameList.findIndex(item=>item.id == e.id)
      if(isShow > -1){
        this.ruleForm.blockNameList.splice(isShow,1)
      }
    },
    // 删除卡名称列表
    handleDel(index,row){
      this.$confirm('是否删除', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          console.log(index)
          this.ruleForm.blockNameList.splice(index,1)
        }).catch(() => {});
    },
    successImg(e) {
      this.ruleForm.activityImg = e
      this.$refs['imgRef'].clearValidate();
    },
    // 删除图片
    handleRemove(){
      this.ruleForm.activityImg = ''
    },
    getTime(e){
      console.log("e",e)
      this.ruleForm.startTime =  e[0] 
      this.ruleForm.endTime = e[1]
      console.log("e",this.ruleForm.startTime)
      console.log("e",this.ruleForm.endTime)
    },
    
    submitForm(formName, status) {
      this.ruleForm.saveStatus = status
      console.log(this.ruleForm);
      //创建确定
      this.$refs[formName].validate(valid => {
        let isCheck = true;
        let isStock = true;
        let isAmount = true;
        if (valid) {
          this.AgreeLoading = true
          
          var data = {
            ...this.ruleForm
          }
          if(this.pathType == 'add'){
            addPackage(data).then(res => {
              setTimeout(() => {
                this.handleClose()
                this.$message.success('创建成功')
                this.$emit('success')
                this.AgreeLoading = false
              }, 1000);
            }).finally(()=>{
              this.AgreeLoading = false
            })
          }else if(this.pathType == 'edit'){
            editPackage(data).then(res => {
              setTimeout(() => {
                this.handleClose()
                this.$message.success('修改成功')
                this.$emit('success')
                this.AgreeLoading = false
              }, 1000);
            }).finally(()=>{
              this.AgreeLoading = false
            })
          }
          
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    editForm(formName, status) {
      //编辑确定
      console.log(this.ruleForm);
      this.$refs[formName].validate(valid => {
        let isCheck = true;
        let isStock = true;
        let isAmount = true;
        if (valid) {
          
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },

    // 富文本框设置
    activityDetailChange(e, index) {
      if (e != "") {
        this.$refs.ruleForm.clearValidate(["activityDetailRef"]);
      }
      // console.log(e,index)
      // console.log(this.ruleForm.)
    }
  }
};
</script>
<style lang="scss" scoped>
.ex-diolog {
  ::v-deep .ex--dialog--footer {
    border: none !important;
    padding: 0 !important;
  }

  ::v-deep .ex--dialog--main {
    padding: 10px 20px !important;
  }
}

.main {
  padding: 20px 20px;
}
.title{
  font-size: 18px;
  font-weight: bold;
  color: #606266;
  padding: 10px 0;
  border-bottom: 2px solid #606266;
  margin-bottom: 20px;
}
.richText {
  border: 1px solid #ccc;
  line-height: normal;
}
.stockNum{
  display: flex;
  justify-content: center;
  padding-top: 10px;
}
.button_box{
  display: flex;
  justify-content: center;
}
</style>
